# 观察者模式的事件分发器
import wx
import wx.lib.newevent as ne
import threading
import time

# 定义自定义事件
myEVT_MY_EVENT = wx.NewEventType()
EVT_MY_EVENT = wx.PyEventBinder(myEVT_MY_EVENT, 1)
class MyEvent(wx.PyCommandEvent):
    def __init__(self, eventType, id):
        super().__init__(eventType, id)
        self.data = None

    def SetData(self, data):
        self.data = data

    def GetData(self):
        return self.data

class EventDispatcher:
    _instance = None
    _observers = []

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def add_observer(self, callback):
        self._observers.append(callback)

    def remove_observer(self, callback):
        self._observers.remove(callback)

    def notify_log_message(self,message):
        self.notify({
            'id': 0, # 日志
            'message': message
        })

    def notify(self, data):
        my_event = MyEvent(myEVT_MY_EVENT, 1)
        my_event.SetData(data)
        # 使用线程安全方式派发事件
        win = wx.GetApp().GetTopWindow()
        #print(message)
        wx.PostEvent(win, my_event)